from docx import Document
from docx.shared import Mm
import os
from PIL import Image


def exif_transpose(img):
    if not img:
        return img

    exif_orientation_tag = 274

    # Check for EXIF data (only present on some files)
    if hasattr(img, "_getexif") and isinstance(img._getexif(), dict) and exif_orientation_tag in img._getexif():
        exif_data = img._getexif()
        orientation = exif_data[exif_orientation_tag]

        # Handle EXIF Orientation
        if orientation == 1:
            # Normal image - nothing to do!
            pass
        elif orientation == 2:
            # Mirrored left to right
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 3:
            # Rotated 180 degrees
            img = img.rotate(180)
        elif orientation == 4:
            # Mirrored top to bottom
            img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 5:
            # Mirrored along top-left diagonal
            img = img.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 6:
            # Rotated 90 degrees
            img = img.rotate(-90, expand=True)
        elif orientation == 7:
            # Mirrored along top-right diagonal
            img = img.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 8:
            # Rotated 270 degrees
            img = img.rotate(90, expand=True)

    return img


if __name__ == '__main__':
    # 要插入的图片所在的文件夹
    fold = r'F:\\测试数据\\图片\\图片\\010006'

    # os.walk(fold)没有返回值，所以这么做显然没有结果，是错的
    # pics=list(os.walk(fold)[3])
    # # pics.pop()
    # print(pics)

    # pics是图片的名字
    # root是string类型， dirs和pics是list类型
    for root, dirs, pics in os.walk(fold):
        doc = Document()
        for i in range(0, len(pics)):

            # 不需要把文件后缀名去掉，后面的PIL库里的open可以直接识别出文件名后缀
            # print(pics[i],'\n')
            # pics[i] = os.path.splitext(pics[i])[0]
            # print(pics[i], '\n')
            if "jpg" in pics[i][-3:] or "JPG" in pics[i][-3:]:
                # 我前半部分的路径直接复制黏贴了，没用root和dirs
                filepath = r'F:\\测试数据\图片\\图片\\010006\\' + pics[i]
                # filepath = root + '\\' + str(pics[i])

                # try:
                pic_tmp = Image.open(filepath)
                pic_tmp = exif_transpose(pic_tmp)
                print(filepath)
                pic_tmp.save('new_1.jpg')
                doc.add_picture(filepath, width=Mm(147))
                os.remove( 'new_1.jpg')

            # except Exception:
            #     pic_tmp = Image.open(filepath)
            #     # 如果格式有问题，就用save转换成默认的jpg格式
            #     pic_tmp.save(pic_tmp)
            #     # 把处理后的图片放进Document变量doc中
            #     doc.add_picture(filepath, width=Mm(147))

            # 把Document变量doc保存到指定路径的docx文件中
            doc.save(r'F:\\测试数据\\图片\\图片\\010006\\p_pic.docx')

            # 输出保存成功的标志
            print("pic", i + 1, "successfully added.")
